<?php

/**
 * Description of CommonAction
 * 后台控制器父类
 * @author xlp
 */
class commonAction extends action {

    //初始化全局信息
    function __construct() {
        parent::__construct();
        T('user/admin');
        //全局获取登录用户数据
        admin::getLoginUser();
        //设置后台模板目录
//        define('GROUP_TPL_DIR', 'content');
//        T('user/permission');
//        permission::checkPermission(admin::$adminInfo['groupid']);
        if (!isAjax()) {
            $this->getSysMenu(); //获取系统菜单
            $this->getAdminMenuSetting(); //获取帐号个性化菜单设置
        }
        //全局获取当前页面URL
        $this->assign(array('adminInfo' => admin::$adminInfo, 'refer' => $this->_get('refer', urlencode(URL))));
        //清除main_path对后台的影响
        G('main_path', null);
    }

    /*
     * 生成系统菜单
     */

    private function getSysMenu() {
        if ($this->_checkLogin(true) && admin::$adminInfo['groupid']) {
            $this->assign(array('sysMenu' => C('menu_group_' . admin::$adminInfo['groupid'])));
            return true;
        }
        return false;
    }

    /*
     * 获取帐号菜单个性设置
     */

    private function getAdminMenuSetting() {
        $adminMenuSetting = F('content/setting/id_' . admin::$adminInfo['id']);
        $list = array('navbar' => 0, 'nav' => 0, 'header' => 0, 'navbg' => 0);
        if ($adminMenuSetting) {
            $list = array_merge($list, $adminMenuSetting);
        }
        $this->assign(array('menuSetting' => $list));
    }

    /*
     * 检查登录，用于必须登录的模块
     * @param 无
     * @return
     */

    protected function _checkLogin($returnBool = false) {
        if (admin::$adminInfo['id']) {
            return true;
        } else {
            if ($returnBool) {
                return false;
            } elseif (isAjax()) {
                return $this->JsonReturn('必须登录后才能进行此操作');
            } else {
                jumpTo(U('login/index'));
            }
            return $returnBool ? false : jumpTo(U('login/index'));
        }
    }

    /*
     * 检查是否管理员
     * @param 无
     * @return bool
     */

    protected function _checkIsAdmin() {
        if (admin::$adminInfo['isAdmin']) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据用户组以及控制器和模块来检查用户操作权限
     * 暂时无效，等待权限控制模块完成再接入
     * @param 无
     * @return
     */
    protected function _checkAdminAuth() {
        return true;
    }

    //设置用户配置信息
    protected function _setAdminSetting($field, $arr = array()) {
        $list = $this->_getDefaultSetting();
        $isHave = M('weixin_setting')->where(array('aid' => 0))->find();

        if ($isHave) {
            $isHave[$field] = isHave($isHave[$field]) ? json_decode($isHave[$field], true) : $list[$field];
            $isHave[$field] = array_merge($isHave[$field], $arr);

            return M('weixin_setting')->update(array($field => json_encode($isHave[$field])), array('aid' => 0));
        } else {
            $list = array_merge($list, array($field => $arr));
            foreach ($list as $k => $v) {
                $list[$k] = json_encode($v);
            }
            $list['aid'] = 0;
//            print_r($list);exit;
            return M('weixin_setting')->insert($list);
        }
    }

    //读取用户配置信息
    protected function _getAdminSetting($field = '*') {
        $setting = M('weixin_setting')->field($field)->where(array('aid' => 0))->find();
        if ($field == '*') {
            return $setting;
        } else {
            if ($setting) {
                $setting = json_decode($setting[$field], true);
            }
            $list = $this->_getDefaultSetting($field);
            foreach ($list as $key => $val) {
                if (!isset($setting[$key])) {
                    $setting[$key] = $val;
                }
            }
            return $setting;
        }
    }

    //默认设置
    protected function _getDefaultSetting($field = '') {
        $init = array(
            'auto_reply' => array(
                'subscribe' => '感谢您的关注！',
                'no_result' => '很抱歉，您要查询的内容不存在',
                'show_bind' => 0,
                'reply_type' => 0,
                'id' => 0,
                'no_result_type' => 0,
                'no_result_id' => 0
            ),
            'user_info' => array(
                'wx_name' => '',
                'wx_logo' => '',
                'wx_id' => '',
                'wx_gh_id' => '',
                'wx_qrcode' => '',
                'wx_AppId' => '',
                'wx_AppSecret' => '',
                'wx_PartnerId' => '',
                'wx_PartnerKey' => '',
                'wx_PaySignKey' => '',
                'is_advanced' => 0
            ),
            'basic_setting' => array(
                'stu_min_quota' => '',
                'stu_max_quota' => '',
                'soc_min_quota' => '',
                'soc_max_quota' => '',
                'handl_rate_max' => '',
                'handl_rate_mid' => '',
                'handl_rate_min' => '',
                'common_rate' => '',
                'gold_rate' => '',
                'over_rate' => '',
                'market_credit' => '',
                'borrow_credit' => '',
                'pay_off_credit' => '',
                'up_credit' => '',
                'esteem_credit_rate' => '',
                'credit_rate' => '',
                'cash_min' => '',
                'repayment_account' => '',
                'service_hotline' => '',
                'service_qq' => '',
                'service_time' => '',
                'account_bank' => '',
                'account_name' => '',
                'iou_content'  => ''
            )
        );
        return $field && isset($init[$field]) ? $init[$field] : $init;
    }

    //处理搜索关键字
    protected function safeSearch($str) {
        return str_replace(array('_', '%', "'", '"'), array('\_', '\%', '', ''), trim($str)); // 把 '_','%'过滤掉;
    }

    //接受无过滤字段内容
    protected function _postContent($field = '', $val = '', $fun = 'stripslashes') {
        return htmlspecialchars_decode($this->_post($field, $val, $fun), ENT_QUOTES);
    }

    //清理过滤
    protected function _clearFilter($content = '', $val = '', $fun = 'stripslashes') {
        return $content ? htmlspecialchars_decode($fun($content), ENT_QUOTES) : $val;
    }

    /*
     * 根据aid获取当前帐号所辖的社区和小区
     * @param $aid int 区域ID
     * @param $type int 获取类型 1:
     */

    //获取城市名称
    protected function getCityName($cityid) {
        static $_city = null;
        if (!$cityid) {
            return '';
        }
        if (!isset($_city[$cityid])) {
            $_city[$cityid] = M('city')->where(array('codeid' => $cityid))->getField('name');
        }
        return $_city[$cityid];
    }

    //获取区域名称
    protected function getAreaName($aid, $field = 'aid') {
        static $_area = null;
        if (!$aid) {
            return '';
        }
        if (!isset($_area[$aid])) {
            $_area[$aid] = M('area')->where(array($field => $aid))->getField('name');
        }
        return $_area[$aid];
    }

    //获取小区名称
    protected function getVillageName($vid) {
        static $_village = null;
        if (!$vid) {
            return '';
        }
        if (!isset($_village[$vid])) {
            $_village[$vid] = M('village')->where(array('vid' => $vid))->getField('title');
        }
        return $_village[$vid];
    }

    //获取小区名称
    protected function _getAdminName($id) {
        static $_admin = null;
        if (!$id) {
            return '';
        }
        if (!isset($_admin[$id])) {
            $_admin[$id] = D('admin')->where(array('id' => $id))->getField('username');
        }
        return $_admin[$id];
    }

    //获取商圈名称
    protected function getBusinessZoneName($id, $returnAll = false) {
        static $_businessZone = null;
        if (!$id) {
            return '';
        }
        if (!isset($_businessZone[$id])) {
            $_businessZone[$id] = M('business_zone')->where(array('zid' => $id))->find();
        }
        return !$returnAll && isset($_businessZone[$id]['ztitle']) ? $_businessZone[$id]['ztitle'] : $_businessZone[$id];
    }

    /*
     * 检查是否需要同步图片到云存储
     */

    protected function _sendImageToYunServer($uploadList) {
        $upConf = C('upload');
        if ($uploadList && $upConf['yun']['open']) {//开启云存储
            T('image/upyun');
            foreach ($uploadList as $key => $val) {
                try {
                    $upyun = new UpYun($upConf['yun']['bucket'], $upConf['yun']['user'], $upConf['yun']['pwd']);
                    $uploadList[$key]['savepath'] = $upConf['yun']['dir'] . ltrim($val['savepath'], $upConf['dir']);
//                z($uploadList[$key]['savepath']);
                    $upyun->writeFile('/' . $uploadList[$key]['savepath'], file_get_contents(ROOT . $val['savepath']), true); // 上传图片，自动创建目录
                } catch (Exception $e) {
//            echo $e->getCode().$e->getMessage();
                }
            }
        }
        return $uploadList;
    }

    /*
     * 获取服务中心缓存
     */

    protected function getServiceCache() {
        return F('steward/service_city_' . admin::$adminInfo['city_id']);
    }


    /*
     * 发送用户消息
     */

    public function sendMemberMessage($uid = 0 , $content = '', $url = '') {
        $objData['uid'] = $uid;
        $objData['content'] = $content;
        if(isHave($url)){
            $url = str_replace('www.', '', $url);
        }
        $objData['linkurl'] = $url;
        $objData['infotime'] = TIME;
        return M('user_msg')->insert($objData);
    }

}
